package com.tongcao.cn.stackoverflow;

import com.google.common.collect.Lists;
import org.apache.commons.io.IOUtils;
import org.apache.commons.lang3.RandomStringUtils;
import org.junit.Test;

import java.io.*;
import java.util.*;

/**
 * @Author:tongcao
 * @Date:2019/3/25 15:28
 * Description:对stackoverflow上Java相关、投票数TOP100的问答进行翻译
 */
public class Top100StackFlowQuestion {


    /**
     * 将InputStream转换为String
     */
    @Test
    public void test1() {
        Scanner scanner = new Scanner(System.in);
        System.out.println();
    }


    /**
     * @param inputStream
     * @return
     */
    private static String convertStreamToString(InputStream inputStream) {
        Scanner scanner = new Scanner(inputStream).useDelimiter("\\A");
        return scanner.hasNext() ? scanner.next() : "";
    }

    private static String convertStreamToString1(InputStream inputStream) {
        try {
            StringWriter sw = new StringWriter();
            IOUtils.copy(inputStream, sw, "UTF-8");
            return sw.toString();
        } catch (IOException e) {
            //todo log
        }
        return "";
    }

    /**
     * Arrays.asList(array)或者Arrays.asList(new Element(1),new Element(2),new Element(3))
     * <p>
     * 不过，这样做有些坑要注意：
     * <p>
     * 这样做生成的list，是定长的。也就是说，如果你对它做add或者remove，都会抛UnsupportedOperationException。
     * 如果修改数组的值，list中的对应值也会改变！
     * <p>
     * Arrays.asList() 返回的是Arrays内部静态类，而不是Java.util.ArrayList的类。这个java.util.Arrays.ArrayList有set(),get(),contains()方法，但是没有任何add() 方法，所以它是固定大小的
     */
    private void convertArrayToList(String... arr) {

        /**
         * 如果希望避免这两个坑，请改用这个方式
         */
        List<String> list = Lists.newArrayList();
        Collections.addAll(list, arr);

    }


    /**
     * Map<Key,Value>基于Value值排序
     */
    public static void sortMaoOfValue() {
        Map<String, Double> map = new HashMap<>();

        ValueComparator valueComparator = new ValueComparator(map);
        Map<String, Object> treeMap = new TreeMap<>(valueComparator);

        map.put("A", 99.5);
        map.put("B", 67.4);
        map.put("C", 67.4);
        map.put("D", 67.3);

        System.out.println("unsorted map: " + map);
        treeMap.putAll(map);
        System.out.println("results:" + treeMap);
    }


    static class ValueComparator implements Comparator<String> {

        Map<String, Double> base;

        public ValueComparator(Map<String, Double> base) {
            this.base = base;
        }

        @Override
        public int compare(String o1, String o2) {
            return base.get(o1) >= base.get(o2) ? 1 : -1;
        }
    }

    public static void randomNum() {

        // 大于等于 0 且 小于 1 的双精度伪随机数
        int num = (int) (Math.random() * 11);

//    那如何产生 “5 <= 随机数 <= 10” 的随机数呢?
        int num1 = 5 + (int) (Math.random() * 6);


        //生成 “2 <= 随机数 <= 11 ” 的随机数
        int num2 = 2 + (int) (Math.random() * (11 - 2 + 1));


        //use RandomUtils


        //org.apache.commons.lang3.RandomStringUtils 提供了生成随机字符串的方法
        System.out.println(RandomStringUtils.randomAlphabetic(100));
        System.out.println(RandomStringUtils.randomNumeric(100));
        System.out.println(RandomStringUtils.randomAlphanumeric(100));
    }

    public enum Blah {
        A, B, C, D
    }

    public static void convertStringToEnum() {

        System.out.println(Blah.valueOf("A"));

    }

    /**
     * A common method for all enums since they can't have another base class
     *
     * @param <T>    Enum type
     * @param c      enum type. All enums must be all caps.
     * @param string case insensitive
     * @return corresponding enum, or null
     */
    public static <T extends Enum<T>> T getEnumFromString(Class<T> c, String string) {
        if (c != null && string != null) {
            try {
                return Enum.valueOf(c, string.trim().toUpperCase());
            } catch (IllegalArgumentException ex) {
            }
        }
        return null;
    }


    /**
     * 编译后的代码
     * String mode = args[0];
     * byte var3 = -1;
     * switch(mode.hashCode()) {
     * case -74056953:
     * if (mode.equals("PASSIVE")) {
     * var3 = 1;
     * }
     * break;
     * case 2537357:
     * if (mode.equals("SAFE")) {
     * var3 = 2;
     * }
     * break;
     * case 1925346054:
     * if (mode.equals("ACTIVE")) {
     * var3 = 0;
     * }
     * }
     *
     * @param args
     */
    public static void testString(String[] args) {
        String mode = args[0];
        switch (mode) {
            case "ACTIVE":
                System.out.println("Application is running on Active mode");
                break;
            case "PASSIVE":
                System.out.println("Application is running on Passive mode");
                break;
            case "SAFE":
                System.out.println("Application is running on Safe mode");
        }
    }

    public static void main(String[] args) throws Exception{
//        sortMaoOfValue();
        randomNum();
        convertStringToEnum();
        System.out.println(getEnumFromString(Blah.class, "D"));
//
//        String[] strings = {"ACTIVE"};
//        testString(strings);

        testversion1L();
    }


    public static void testversion1L() throws Exception {
        File file = new File("person.out");
        // 序列化
        ObjectOutputStream oout = new ObjectOutputStream(new FileOutputStream(file));
        Person person = new Person("John", 21, "广州");
        oout.writeObject(person);
        oout.close();
        // 反序列化
        ObjectInputStream oin = new ObjectInputStream(new FileInputStream(file));
        Object newPerson = oin.readObject();
        oin.close();
        System.out.println(newPerson);
    }
}
